package chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/** 
 * Contains a straightforward main that implements the server side of a half-duplex (look it up)
 * chat program based on text strings sent over TCP connection between client and server. 
 * 
 * @see EchoClient for client side.
 * @author Lom Hillah
 * @author Justin Templemore
 *
 */
public class EchoServer {

	/**
	 * Server logic of the simple chat program.
	 */
	public static void main(String[] args) 
	{
		ServerSocket serverSocket = null;
		try 
		{
			// display local host information (very useful for setting up a conxn from the client)
			InetAddress localhost = InetAddress.getLocalHost();
			System.out.println ("Local host  is " + localhost);
			// open a server socket that listens for socket connections (clients) on port 4444
			serverSocket = new ServerSocket(4444);
			System.out.println("Started Echo server");
		} 
		catch (IOException e)
		{
			// only one server / application (Java or not) bind to and listen on a port at one time
			System.out.println("Could not listen on port 4444, check that it is not already in use.");
			System.exit(-1);
		}
		// When the remote client connects, we get a mirror opposite Socket object for bidir comm.
		Socket clientSocket = null;
		try 
		{
			clientSocket = serverSocket.accept();
			System.out.println("Accepted client from: " + clientSocket.getInetAddress());
		} 
		catch (IOException e) 
		{
			// if there is a generic IO error setting up the connection
			System.out.println("Accept failed: 4444");
			System.exit(-1);
		}
		// We now have the opposite end of the remote client's socket, we can communicate.
		// Info sent on our end's out arrives on the remote end's in, and vice versa.
		PrintWriter outToClient = null;
		BufferedReader inFromClient = null;
		BufferedReader inFromConsole = new BufferedReader (new InputStreamReader(System.in)); 
		try 
		{
			// set up Readers and Writers to read and write text from/to the client
			outToClient = new PrintWriter (clientSocket.getOutputStream(), true);
			inFromClient = new BufferedReader (new InputStreamReader(clientSocket.getInputStream()));
			String messageFromClient, messageToClient;
			// continue until the socket is closed (readLine returns null)
			while ((messageFromClient = inFromClient.readLine()) != null) 
			{
				System.out.println("client says : " + messageFromClient);
				System.out.print("> ");
				messageToClient = inFromConsole.readLine();
				System.out.println();
				outToClient.println(messageToClient);
				if (messageToClient.equalsIgnoreCase ("Bye.")) 
				{
					System.out.println("Server says goodbye. Quitting.");
					break;
				}
			}
			serverSocket.close();
		} 
		catch (IOException ioe) 
		{
			System.out.println("General IO failure (network connection lost, etc)");
			System.exit(-1);
		}
	}
}
